package org.teamh.artificialIntelligenceEasy;

import java.io.BufferedReader;
import java.io.EOFException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

import org.teamh.connection.Connection;
import org.teamh.connection.json.NOOP;
import org.teamh.game.Start;
import org.teamh.logic.Logic;
import org.teamh.logic.lobby.ModelManager;

/**
 * This class is the basic class of the artificial intelligence. It is
 * responsible for the startup of all necessary threads and dependencies. This
 * is mainly the AI Thread, the network connection and the datamodel.
 * Furthermore, the socket Thread is opening for a remote diagnose possibilty.
 * 
 * @author richard
 * 
 */
public class StartAI extends Start{
	
	public StartAI(String name, String password, String game) {
		setConnection(new Connection(this));
		setInterfaceManager(new AIInterfaceManager(this, name, password, game));
		setLogic(new Logic(this));
		setModel(new ModelManager(this));
	}
	
	/**
	 * Creates a new instance of an artificial intelligence within a new java
	 * vm. It can then only be accesed via a socket connection.
	 * 
	 * @param name
	 * @param password
	 * @param game
	 */
	public static void create(final String name, final String password, final String game) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					String s = null;
					ProcessBuilder pb = new ProcessBuilder("java",  "-cp", System.getProperty("java.class.path"),
							"org.teamh.artificialIntelligence.StartAI", name, password, game);
					pb.directory(new File("bin"));
					Process p = pb.start();
					BufferedReader stdInput = new BufferedReader(new InputStreamReader(
							p.getInputStream()));

					BufferedReader stdError = new BufferedReader(new InputStreamReader(
							p.getErrorStream()));

					while ((s = stdInput.readLine()) != null) {
						System.out.println(s);
					}

					while ((s = stdError.readLine()) != null) {
						System.out.println(s);
					}

				} catch (EOFException eof) {
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}
	
	@Override
	public void exit() {
		super.exit();
		
		NOOP.stop();
	}
	
	/**
	 * Main method to start the ai. 
	 * @param args
	 * @throws FileNotFoundException 
	 */
	public static void main(String[] args) throws FileNotFoundException {
//		StartGame.PRINT_MESSAGES = true;

//		if(!StartGame.PRINT_MESSAGES) {
//			System.setOut(new PrintStream(System.getProperty("user.home") + "/textout"));
//			System.setErr(new PrintStream(System.getProperty("user.home") + "/errOut"));
//		}
		
		if(args.length < 3) {
			args = new String[]{"davkro", "labtec3445", "123466"};
		}
		
		if(args.length >= 3) {
			StartAI start = new StartAI(args[0], args[1], args[2]);
			start.startCore();
		}
	}
}
